<template>
  <div class="device-settings">
    <el-row :gutter="20">
      <!-- 设备状态上报 -->
      <el-col :span="12">
        <el-card title="设备状态上报">
          <div class="device-report">
            <el-descriptions :column="1" border>
              <el-descriptions-item label="最后上报时间">
                {{ lastReportTime || '尚未上报' }}
              </el-descriptions-item>
            </el-descriptions>
            <el-button 
              type="primary" 
              @click="uploadDeviceStatus" 
              :loading="uploading"
              style="margin-top: 15px;"
            >
              <el-icon><Upload /></el-icon>
              {{ uploading ? '上报中...' : '立即上报设备状态' }}
            </el-button>
          </div>
        </el-card>
      </el-col>
      
      <!-- 系统管理 -->
      <el-col :span="12">
        <el-card title="系统操作">
          <el-space direction="vertical" style="width: 100%;" size="large">
            <!-- 系统操作 -->
            <div class="system-actions">
              <el-space wrap>
                <el-button type="warning" @click="rebootSystem">
                  <el-icon><Refresh /></el-icon>
                  重启系统
                </el-button>
                <el-button type="danger" @click="shutdownSystem">
                  <el-icon><SwitchButton /></el-icon>
                  关闭系统
                </el-button>
                <el-button @click="exportLogs">
                  <el-icon><Download /></el-icon>
                  导出日志
                </el-button>
                <el-button @click="clearCache">
                  <el-icon><Delete /></el-icon>
                  清理缓存
                </el-button>
              </el-space>
            </div>
            
            <!-- 系统更新 -->
            <div class="update-management">
              <h4>系统更新</h4>
              <el-alert 
                v-if="updateInfo.has_update"
                title="发现新版本" 
                type="warning"
                :description="`新版本 ${updateInfo.version} 可用，当前版本: ${updateInfo.current_version}`"
                show-icon
                style="margin-bottom: 10px;"
              />
              <el-space>
                <el-button type="primary" @click="checkUpdates">
                  <el-icon><Search /></el-icon>
                  检查更新
                </el-button>
                <el-button 
                  v-if="updateInfo.has_update"
                  type="success" 
                  @click="installUpdate"
                  :loading="updating"
                >
                  <el-icon><Download /></el-icon>
                  {{ updating ? '更新中...' : '安装更新' }}
                </el-button>
              </el-space>
            </div>
            
            <!-- 存储管理 -->
            <div class="storage-management">
              <h4>存储管理</h4>
              <el-progress 
                :percentage="storageInfo.usage_percent" 
                :stroke-width="15"
                :color="getStorageColor(storageInfo.usage_percent)"
              />
              <p style="margin-top: 10px;">
                已使用: {{ formatBytes(storageInfo.used) }} / {{ formatBytes(storageInfo.total) }}
              </p>
              <el-button @click="cleanupStorage">
                <el-icon><Delete /></el-icon>
                清理存储
              </el-button>
            </div>
          </el-space>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 设备信息 -->
    <el-row style="margin-top: 20px;">
      <el-col :span="24">
        <el-card title="设备信息">
          <el-descriptions :column="3" border>
            <el-descriptions-item label="设备ID">{{ deviceInfo.device_id }}</el-descriptions-item>
            <el-descriptions-item label="设备名称">{{ deviceInfo.hostname }}</el-descriptions-item>
            <el-descriptions-item label="IP地址">{{ deviceInfo.ip_address }}</el-descriptions-item>
            <el-descriptions-item label="操作系统">{{ deviceInfo.os_info }}</el-descriptions-item>
            <el-descriptions-item label="内核版本">{{ deviceInfo.kernel_version }}</el-descriptions-item>
            <el-descriptions-item label="架构">{{ deviceInfo.architecture }}</el-descriptions-item>
            <el-descriptions-item label="系统版本">{{ deviceInfo.version }}</el-descriptions-item>
            <el-descriptions-item label="运行时间">{{ deviceInfo.uptime }}</el-descriptions-item>
            <el-descriptions-item label="最后更新">{{ deviceInfo.last_update }}</el-descriptions-item>
          </el-descriptions>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 设备上报日志 -->
    <el-row style="margin-top: 20px;">
      <el-col :span="24">
        <el-card>
          <template #header>
            <div style="display: flex; justify-content: space-between; align-items: center;">
              <span>设备上报日志</span>
              <el-button type="primary" size="small" @click="fetchDeviceLogs">
                <el-icon><Refresh /></el-icon>
                刷新日志
              </el-button>
            </div>
          </template>
          <div class="logs-container">
            <div v-if="deviceLogs.length === 0" class="no-logs">
              暂无日志信息
            </div>
            <div v-else class="logs-content">
              <div 
                v-for="(log, index) in deviceLogs" 
                :key="index" 
                class="log-line"
                :class="getLogLineClass(log)"
              >
                {{ log }}
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

export default {
  name: 'DeviceSettings',
  setup() {
    const updateInfo = reactive({
      has_update: false,
      current_version: '1.0.0',
      version: '1.1.0'
    })
    
    const storageInfo = reactive({
      used: 28.5 * 1024 * 1024 * 1024,      // 28.5GB
      total: 64 * 1024 * 1024 * 1024,       // 64GB
      usage_percent: 44.5
    })
    
    const deviceInfo = reactive({
      device_id: 'N/A',
      hostname: '',
      ip_address: '',
      os_info: '',
      kernel_version: '',
      architecture: '',
      version: '',
      uptime: '',
      last_update: ''
    })
    
    const updating = ref(false)
    const uploading = ref(false)
    const lastReportTime = ref('')
    const deviceLogs = ref([])
    
    const formatBytes = (bytes) => {
      if (bytes === 0) return '0 B'
      const k = 1024
      const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    }
    
    const getStorageColor = (percent) => {
      if (percent > 90) return '#F56C6C'
      if (percent > 75) return '#E6A23C'
      return '#67C23A'
    }
    
    /* 手动上报设备状态 */
    const uploadDeviceStatus = async () => {
      uploading.value = true
      try {
        await axios.post('/api/device/report')
        lastReportTime.value = new Date().toLocaleString()
        ElMessage.success('设备状态已上报')
        // 上报成功后自动刷新日志
        setTimeout(() => {
          fetchDeviceLogs()
        }, 1000)
      } catch (error) {
        console.error('设备状态上报失败:', error)
        ElMessage.error('设备状态上报失败')
      } finally {
        uploading.value = false
      }
    }

    /* 获取最后上报时间 */
    const fetchLastReportTime = async () => {
      try {
        const res = await axios.get('/api/device/last-report')
        if (res.data.status === 'success') {
          lastReportTime.value = new Date(res.data.last_report_time).toLocaleString()
        }
      } catch (error) {
        // 忽略错误，可能还没有上报过
        console.log('获取最后上报时间失败:', error)
      }
    }

    /* 获取设备信息 */
    const fetchDeviceInfo = async () => {
      try {
        const res = await axios.get('/api/system/info')
        if (res.data.status === 'success') {
          const data = res.data.data
          deviceInfo.device_id = data.box_id
          deviceInfo.hostname = data.hostname
          deviceInfo.ip_address = data.ip_address || ''
          deviceInfo.os_info = data.os
          deviceInfo.kernel_version = data.kernel
          deviceInfo.architecture = data.arch
          deviceInfo.version = data.version
          deviceInfo.last_update = new Date().toLocaleString()
          // 简单转换 uptime 秒数为可读
          const seconds = Math.floor(data.uptime)
          const days = Math.floor(seconds / 86400)
          const hours = Math.floor((seconds % 86400) / 3600)
          const minutes = Math.floor((seconds % 3600) / 60)
          deviceInfo.uptime = `${days}天 ${hours}小时 ${minutes}分钟`
        }
      } catch (e) {
        console.error('获取设备信息失败:', e)
      }
    }
    
    const rebootSystem = async () => {
      try {
        await ElMessageBox.confirm('确定要重启系统吗？', '重启确认', { type: 'warning' })
        await axios.post('/api/system/reboot')
        ElMessage.warning('系统重启指令已发送')
      } catch (error) {
        if (error !== 'cancel') {
          console.error('重启系统失败:', error)
          ElMessage.error('重启系统失败')
        }
      }
    }
    
    const shutdownSystem = async () => {
      try {
        await ElMessageBox.confirm('确定要关闭系统吗？', '关机确认', { type: 'warning' })
        await axios.post('/api/system/shutdown')
        ElMessage.warning('系统关机指令已发送')
      } catch (error) {
        if (error !== 'cancel') {
          console.error('关闭系统失败:', error)
          ElMessage.error('关闭系统失败')
        }
      }
    }
    
    const exportLogs = async () => {
      try {
        const response = await axios.get('/api/system/logs/export', { responseType: 'blob' })
        const url = window.URL.createObjectURL(new Blob([response.data]))
        const link = document.createElement('a')
        link.href = url
        link.setAttribute('download', `mobox-logs-${new Date().toISOString().split('T')[0]}.zip`)
        document.body.appendChild(link)
        link.click()
        link.remove()
        ElMessage.success('日志导出成功')
      } catch (error) {
        console.error('导出日志失败:', error)
        ElMessage.error('导出日志失败')
      }
    }
    
    const clearCache = async () => {
      try {
        await axios.post('/api/system/clear-cache')
        ElMessage.success('缓存清理完成')
      } catch (error) {
        console.error('清理缓存失败:', error)
        ElMessage.error('清理缓存失败')
      }
    }
    
    const checkUpdates = async () => {
      try {
        const response = await axios.get('/api/system/check-updates')
        Object.assign(updateInfo, response.data)
        if (updateInfo.has_update) {
          ElMessage.warning(`发现新版本 ${updateInfo.version}`)
        } else {
          ElMessage.success('当前已是最新版本')
        }
      } catch (error) {
        console.error('检查更新失败:', error)
        ElMessage.error('检查更新失败')
      }
    }
    
    const installUpdate = async () => {
      try {
        await ElMessageBox.confirm('更新过程中系统可能会重启，确定继续吗？', '更新确认', { type: 'warning' })
        updating.value = true
        await axios.post('/api/system/install-update')
        ElMessage.success('更新已开始，系统将在更新完成后重启')
      } catch (error) {
        if (error !== 'cancel') {
          console.error('安装更新失败:', error)
          ElMessage.error('安装更新失败')
        }
        updating.value = false
      }
    }
    
    const cleanupStorage = async () => {
      try {
        await axios.post('/api/system/cleanup-storage')
        // 模拟清理后的存储变化
        storageInfo.used *= 0.8
        storageInfo.usage_percent = (storageInfo.used / storageInfo.total) * 100
        ElMessage.success('存储清理完成')
      } catch (error) {
        console.error('清理存储失败:', error)
        ElMessage.error('清理存储失败')
      }
    }
    
    /* 获取设备日志 */
    const fetchDeviceLogs = async () => {
      try {
        const res = await axios.get('/api/device/logs')
        if (res.data.status === 'success') {
          deviceLogs.value = res.data.logs || []
        }
      } catch (error) {
        console.error('获取设备日志失败:', error)
        ElMessage.error('获取设备日志失败')
      }
    }
    
    /* 判断日志行样式 */
    const getLogLineClass = (log) => {
      if (log.includes('ERROR') || log.includes('error')) return 'log-error'
      if (log.includes('WARNING') || log.includes('warning')) return 'log-warning'
      if (log.includes('SUCCESS') || log.includes('success')) return 'log-success'
      return 'log-normal'
    }
    
    onMounted(() => {
      fetchDeviceInfo()
      fetchLastReportTime()
      fetchDeviceLogs()
    })
    
    return {
      updateInfo,
      storageInfo,
      deviceInfo,
      updating,
      uploading,
      lastReportTime,
      deviceLogs,
      formatBytes,
      getStorageColor,
      uploadDeviceStatus,
      fetchDeviceInfo,
      fetchLastReportTime,
      fetchDeviceLogs,
      getLogLineClass,
      rebootSystem,
      shutdownSystem,
      exportLogs,
      clearCache,
      checkUpdates,
      installUpdate,
      cleanupStorage
    }
  }
}
</script>

<style scoped>
.device-settings {
  padding: 0;
}

.device-report h4,
.system-actions h4,
.update-management h4,
.storage-management h4 {
  margin: 0 0 15px 0;
  color: #303133;
  font-size: 16px;
}

.logs-container {
  max-height: 400px;
  overflow-y: auto;
  background-color: #f5f5f5;
  border-radius: 4px;
  padding: 10px;
}

.no-logs {
  text-align: center;
  color: #909399;
  padding: 20px;
}

.logs-content {
  font-family: 'Courier New', Consolas, monospace;
  font-size: 12px;
  line-height: 1.4;
}

.log-line {
  margin-bottom: 4px;
  padding: 2px 4px;
  border-radius: 2px;
  word-break: break-all;
}

.log-normal {
  color: #606266;
}

.log-error {
  color: #F56C6C;
  background-color: #fef0f0;
}

.log-warning {
  color: #E6A23C;
  background-color: #fdf6ec;
}

.log-success {
  color: #67C23A;
  background-color: #f0f9ff;
}
</style> 